package com.lvcoding.authserver.config;

import com.lvcoding.common.User;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Arrays;

/**
 * web安全配置
 * @author wuyanshen
 */
@Configuration
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // auth.inMemoryAuthentication()
        //         .withUser("admin")
        //         .password(passwordEncoder().encode("123"))
        //         .authorities("u:admin:view")
        //         .and()
        //         .withUser("jack")
        //         .password(passwordEncoder().encode("123"))
        //         .authorities("u:common:view");
        auth.userDetailsService(userDetailsService);
    }

    // @Bean
    // @Override
    // protected UserDetailsService userDetailsService() {
    //     return username -> {
    //         User user = new User();
    //         if ("admin".equals(username)) {
    //             user.setUsername("admin");
    //             user.setPassword(passwordEncoder().encode("123"));
    //             user.setAuthorities(Arrays.asList("u:admin:view"));
    //         } else {
    //             user.setUsername("jack");
    //             user.setPassword(passwordEncoder().encode("123"));
    //             user.setAuthorities(Arrays.asList("u:common:view"));
    //         }
    //         return user;
    //     };
    // }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/oauth/**", "/login/**").permitAll()
                .and()
                .formLogin();
    }
}
